import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react'
import './style.less'
import { useSearchParams, useNavigate } from 'react-router-dom'
import { Button, Space, Row, Col, Form, Input, List, Popconfirm, Flex } from 'antd'
import { HsAdminForm, HsAdminInput, HsAdminSpin } from '@hs-admin/base-components'
import { CloseCircleOutlined } from '@ant-design/icons'
import { useImmer } from 'use-immer'
import { HsAdminSelectDomain, HsAdminSelectUsers } from '@/components/global'
import DataItemDetail from '../ItemDetail'
import { getAllMapOptions, reqDataMapAdd, reqDataMapEdit, reqMapInfor } from '@/api/assetMaintain/industry/atlas'
import { message } from '@hs-admin/utils'
import { reqDataItemList } from '@hs-admin/api'

const OperationIndustryAtlasDetail: React.FC = () => {
  const navigate = useNavigate()
  const [searchParams] = useSearchParams()
  const id: string | null = searchParams.get('id') ? searchParams.get('id') : null

  const [mapOptions, setmapOptions] = useState([])
  const [domainOptions, setdomainOptions] = useState<any[]>([])
  const [form] = Form.useForm()
  const [formValues, setformValues] = useImmer<any>({})
  const [userOptions, setuserOptions] = useState<any[]>([])
  const [loading, setloading] = useState(false)

  // 图谱选择
  const handleSelect_name = useCallback(
    (value: string, option: { label: any }) => {
      form.setFieldValue('show_map_id', value)
      setformValues((prev: { map_name: string }) => {
        prev.map_name = option.label
      })
    },
    [form, setformValues]
  )
  const formItemOptions = useMemo(
    () => [
      {
        label: '图谱选择',
        name: 'map_id',
        component: 'Select',
        required: true,
        componentProps: {
          options: mapOptions,
          onChange: (value: string, option: { label: string }) => handleSelect_name(value, option)
        },
        FormItemColProps: {
          span: 12
        }
      },
      {
        label: '所属领域',
        name: 'domain_id',
        slot: 'domain_id',
        required: true,
        FormItemColProps: {
          span: 12
        }
      },
      {
        label: '产业数仓名称',
        name: 'name',
        component: 'Input',
        required: true,
        FormItemColProps: {
          span: 12
        }
      },
      {
        label: '',
        name: 'inforTitle',
        slot: 'inforTitle',
        FormItemColProps: {
          span: 24
        }
      },
      {
        label: '图谱ID',
        name: 'show_map_id',
        component: 'InputNumber',
        required: true,
        FormItemColProps: {
          span: 12
        },
        componentProps: {
          disabled: true
        }
      },
      {
        label: '负责人',
        name: 'contacts_id',
        required: true,
        FormItemColProps: {
          span: 12
        },
        slot: 'contacts_id'
      },
      {
        label: '',
        name: 'priceTitle',
        slot: 'priceTitle'
      },
      {
        label: '全国',
        name: ['prices', 'national'],
        slot: 'national',
        FormItemColProps: {
          span: 12
        }
      },
      {
        label: '省级',
        name: ['prices', 'provincial'],
        slot: 'provincial',
        FormItemColProps: {
          span: 12
        }
      },
      {
        label: '市级',
        name: ['prices', 'city'],
        slot: 'city',
        FormItemColProps: {
          span: 12
        }
      },
      {
        label: '区、县、园区',
        name: ['prices', 'district'],
        slot: 'district',
        FormItemColProps: {
          span: 12
        }
      },
      {
        label: '产业数仓描述',
        name: 'description',
        component: 'TextArea',
        required: true,
        FormItemProps: {
          labelCol: { span: 3 },
          wrapperCol: { span: 21 }
        }
      },
      {
        label: '产业数仓边界(包含的国民经济分类)',
        name: 'border',
        component: 'TextArea',
        required: true,
        componentProps: {
          maxLength: 1500
        },
        FormItemProps: {
          labelCol: { span: 3 },
          wrapperCol: { span: 21 },
          className: 'break-form-item-text'
        }
      }
    ],
    [mapOptions, handleSelect_name]
  )
  const [dataItems, setdataItems] = useImmer<any[]>([])
  const [originDataItems, setOriginDataItems] = useImmer<any[]>([])
  const [searchValue, setsearchValue] = useState('')
  const dataItemDetailRef = useRef<any>(null)
  const data_item_product_ids = useMemo(() => originDataItems.map((item: { id: any }) => item.id), [originDataItems])

  const goList = () => {
    navigate('/operationIndustry/atlas', {
      state: {
        params: {
          breadType: 'reset'
        }
      }
    })
  }
  // 图谱
  const getIndustryMapList = async () => {
    const params = {
      page: 1,
      page_size: 1000
    }
    const res = await getAllMapOptions(params)
    const list = res.items.map((item: any) => ({
      label: item.map_name,
      value: +item.graph_code
    }))
    setmapOptions(list)
  }

  const getDataItem = () => {
    reqDataItemList({
      industry_map_id: id,
      page_size: 99
    }).then((res) => {
      setdataItems(res.items)
      setOriginDataItems(res.items)
    })
  }
  // 图谱详情
  const getMapInfor = async () => {
    const params = {
      id
    }
    const res = await reqMapInfor(params)
    const model = {
      ...res
    }
    form.setFieldsValue({
      ...model,
      show_map_id: model.map_id
    })
    setformValues(model)
    setuserOptions([
      {
        label: model.contacts.name,
        value: model.contacts.id
      }
    ])
    setdomainOptions([
      {
        label: model.industry_domain.name,
        value: model.industry_domain.id
      }
    ])
    getDataItem()
  }

  const search = () => {
    setdataItems(originDataItems.filter((item: { name: string | string[] }) => item.name.includes(searchValue)))
  }
  const openDataItem = (item: any = {}) => {
    dataItemDetailRef.current.showModal(item, id)
  }
  const deleteDataItem = async (item: any) => {
    setdataItems((prev) => {
      const index = prev.findIndex((ele) => ele.id === item.id)
      prev.splice(index, 1)
    })
    setOriginDataItems((prev) => {
      const originIndex = prev.findIndex((ele) => ele.id === item.id)
      prev.splice(originIndex, 1)
    })
  }
  // 保存和提交上架审批
  const handleOk = async (flag: boolean) => {
    form
      .validateFields()
      .then(async (values) => {
        setloading(true)
        const {
          prices: { national, provincial, city, district }
        } = values
        const params = {
          ...formValues,
          ...values,
          data_item_product_ids: originDataItems.map((item) => item.id),
          prices: {
            national: national || null,
            provincial: provincial || null,
            city: city || null,
            district: district || null
          },
          status: flag ? 'wait_for_audit' : 'draft'
        }
        Reflect.deleteProperty(params, 'industry_domain')
        Reflect.deleteProperty(params, 'inforTitle')
        Reflect.deleteProperty(params, 'priceTitle')
        if (!id) {
          try {
            await reqDataMapAdd(params)
            message.success(flag ? '提交上架审批成功' : '保存成功')
            goList()
          } catch (error) {
            return Promise.reject(error)
          } finally {
            setloading(false)
          }
        } else {
          try {
            await reqDataMapEdit(params)
            message.success(flag ? '提交上架审批成功' : '保存成功')
            goList()
          } catch (error) {
            return Promise.reject(error)
          } finally {
            setloading(false)
          }
        }
      })
      .catch((error) => {
        return Promise.reject(error)
      })
  }
  const addDataItemList = (item: { id: any }) => {
    setdataItems((prev) => {
      prev.push(item)
    })
    setOriginDataItems((prev) => {
      prev.push(item)
    })
  }

  useEffect(() => {
    getIndustryMapList()
    if (id) {
      getMapInfor() // 获取详情
    }
  }, [id])

  return (
    <div className="operation-industry-atlas-detail-wrapper">
      {loading && <HsAdminSpin />}
      <div className="top">
        <div className="top_title">
          <div>{id ? '编辑' : '新增'}图谱</div>
          <CloseCircleOutlined onClick={goList} />
        </div>
      </div>
      <br />
      <div className="mid">
        <HsAdminForm form={form} formItemOptions={formItemOptions} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} labelAlign="right">
          <div slot="domain_id">
            <HsAdminSelectDomain placeholder="请选择所属领域" options={domainOptions} />
          </div>
          <div slot="inforTitle">
            <Row>
              <Col span={4} offset={2}>
                <b>图谱信息：</b>
              </Col>
            </Row>
          </div>
          <div slot="priceTitle">
            <Row>
              <Col span={4} offset={2}>
                <b>产业数仓价格：</b>
              </Col>
            </Row>
          </div>
          <div slot="contacts_id">
            <Form.Item name="contacts_id">
              <HsAdminSelectUsers placeholder="请选择负责人" options={userOptions}></HsAdminSelectUsers>
            </Form.Item>
          </div>
          <div slot="national">
            <Flex align="center">
              <Form.Item name={['prices', 'national']} noStyle>
                <Input type="number" />
              </Form.Item>
              <div className="flex-none ml-2">元/年</div>
            </Flex>
          </div>
          <div slot="provincial">
            <Flex align="center">
              <Form.Item name={['prices', 'provincial']} noStyle>
                <Input type="number" />
              </Form.Item>
              <div className="flex-none ml-2">元/年</div>
            </Flex>
          </div>
          <div slot="city">
            <Flex align="center">
              <Form.Item name={['prices', 'city']} noStyle>
                <Input type="number" />
              </Form.Item>
              <div className="flex-none ml-2">元/年</div>
            </Flex>
          </div>
          <div slot="district">
            <Flex align="center">
              <Form.Item name={['prices', 'district']} noStyle>
                <Input type="number" />
              </Form.Item>
              <div className="flex-none ml-2">元/年</div>
            </Flex>
          </div>
        </HsAdminForm>
        <br />
        <div>
          <b>数据项：</b>
        </div>
        <br />
        <Space className="flex justify-between">
          <Space>
            <HsAdminInput value={searchValue} onChange={(e: { target: { value: React.SetStateAction<string> } }) => setsearchValue(e.target.value)} />
            <Button type="primary" onClick={search}>
              搜索
            </Button>
          </Space>
          <Button type="primary" onClick={openDataItem}>
            新增数据项
          </Button>
        </Space>
        <br />
        <List
          dataSource={dataItems}
          renderItem={(item) => (
            <List.Item
              actions={[
                <Popconfirm
                  title="警告"
                  description="确定删除该项吗?"
                  onConfirm={() => {
                    deleteDataItem(item)
                  }}>
                  <Button type="link">删除</Button>
                </Popconfirm>
              ]}>
              <List.Item.Meta title={<a>{item.name}</a>} description={item.description} />
            </List.Item>
          )}
        />
        <Space className="flex justify-end">
          <Button type="primary" onClick={goList}>
            取消
          </Button>
          <Button type="primary" onClick={() => handleOk(false)}>
            保存
          </Button>
          {formValues.status !== 'published' && (
            <Button type="primary" onClick={() => handleOk(true)}>
              提交上架审批
            </Button>
          )}
        </Space>
      </div>
      <DataItemDetail ref={dataItemDetailRef} dataItemProductIds={data_item_product_ids} finish={addDataItemList} />
    </div>
  )
}

export default OperationIndustryAtlasDetail
